package access;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;

public class Student {
	
	private File file ;
	private byte[] buffer = new byte[ 30 ]; // 数组默认值都是 0
	private Charset charset = Charset.forName( "UTF-8" );
	private final byte byteValue = 0 ;
	
	public Student( String filename ) {
		this.file = new File( filename );
	}
	
	public void save( int id , String name , char gender ) throws IOException {
		OutputStream out = new FileOutputStream( file );
		DataOutputStream dos = new DataOutputStream( out );
		
		dos.writeInt( id ); // 用 4 字节保存 id 
		
		Arrays.fill( buffer , byteValue );
		
		// 将 name 按照 UTF-8 编码为 字节序列
		byte[] bytes = name.getBytes( charset );
		// 将 bytes 中的 字节 拷贝到 buffer 中
		System.arraycopy( bytes , 0 ,  buffer , 0 , Math.min( buffer.length , bytes.length ) );
		dos.write( buffer ); // 将 buffer 中的全部字节写出
		dos.writeChar( gender ); // 用 2 字节保存 gender
		
		dos.close();
		out.close();
	}
	
	public void list() throws IOException {
		
		InputStream in = new FileInputStream( file );
		DataInputStream dis = new DataInputStream( in );
		
		int id = dis.readInt(); // 读取四个字节重构一个 int 值
		
		dis.readFully( buffer ); // 读取 buffer.length 个字节到 buffer 数组中
		String name = new String( buffer , charset );
		name = name.trim(); // 剔除首尾空白 (主要是剔除尾部空白)
		
		char gender = dis.readChar(); // 读取两个字节重构一个 char 值
		
		dis.close();
		in.close();
		
		System.out.println( id + " , " + name + " , " + gender );
		
	}

	public static void main(String[] args) throws IOException {
		
		Student s = new Student( "first.dat" );
		
		s.save( 9527 , "华府高级伴读小书童华安", '男' );
		
		s.list();

	}

}
